#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>

int main()
{
    pid_t id = fork();
    assert(id != -1);

    if(id== 0)
    {
        int cnt = 5;
        while(cnt)
        {
            //child
            printf("child runing pid:%d ppid:%d cnt:%d \n",getpid(),getppid(),cnt);
            cnt--;
            sleep(1);
        }
        exit(4);
    }
    //parent
    int status = 0;
    while(1)
    {
        
        pid_t ret = waitpid(id+1,&status,WNOHANG);//0表示阻塞状态-----WNOHANG为非阻塞状态，父进程偶尔查看，然后返回可做自己的事情
        if(ret==0)
        {
            printf("child runing......\n");
            //child no success
            //todo
        }
        else if(ret==id)
        {
            printf("wait success,exit code:%d ,sig:%d \n ",(status>>8)&0xFF,status&0x7F);
            //child success
            //wait success
            break;
        }
        else 
        {
            printf("pid X!\n");
            //id出错，返回-1,ret=-1
            break;
        }
        sleep(1);
    }

}
